package com.zlyx.easy.core.utils;

import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;

import com.zlyx.easy.core.loggers.Logger;

/**
 * @Auth 赵光
 * @Describle
 * @2019年6月25日 下午4:14:44
 */
public class HostUtils {

	private static String host = getHost();

	/**
	 * 判断是否当前服务
	 * 
	 * @param host
	 * @return
	 */
	public static boolean isCurrentServcer(String host) {
		return HostUtils.host.equals(host);
	}

	/**
	 * 获取当前服务host地址
	 * 
	 * @return
	 */
	public static String getHost() {
		try {
			return "http://" + getLocalIP() + ":" + getLocalPort() + "/";
		} catch (Exception e) {
			Logger.err(e);
		}
		return "127.0.0.1";
	}

	/**
	 * 获取当前服务端口
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getLocalPort() throws Exception {
		MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
		Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
				Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
		if (objectNames.toString().contains("port")) {
			return objectNames.iterator().next().getKeyProperty("port");
		}
		return "8080";
	}

	/**
	 * 获取当前服务端口
	 * 
	 * @return
	 */
	public static String getLocalIP() {
		try {
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress ip = addresses.nextElement();
					if (ip != null && ip instanceof Inet4Address && !ip.isLoopbackAddress()
							&& ip.getHostAddress().indexOf(":") == -1) {
						return ip.getHostAddress();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
